"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : WDR
Case Name   : 开启数据库监控快照功能,验证超过快照数量最大值是否清理（涉及参数均修改）
Create At   : 2023.1.13
Owner       : opentestcase009
Description :
    1、修改参数，开启快照功能
    2、设置数据库监控快照数据的保留天数为1,设置自动对数据库监控数据执行快照操作的时间间隔为30min
    3、手动生成快照,循环50次,查看snapshot_id最小的快照数据是否被清理(最大数量通过计算为48)
    4、使用默认系统库，查看快照数据
    5、清理环境，恢复参数
Expect      :
    1、开启快照功能成功
    2、设置修改参数成功
    3、循环手动生成快照数据成功
    4、查看快照数据成功，超过快照数量最大值后，snapshot_id较小的数据被清理
    5、清理环境成功，恢复参数成功
History     :
    modified by opentestcase009 at 2023.11.16:因环境性能问题优化用例中sleep时长
"""

import os
import time
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class WDR(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.sh_pri = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.config_wdr = "enable_wdr_snapshot"
        self.config_retention = "wdr_snapshot_retention_days"
        self.config_interval = "wdr_snapshot_interval"
        self.table = 'snapshot.snapshot'

    def test_wdr(self):
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        text = '-----step1:检查参数，修改参数配置;expect:成功-----'
        self.log.info(text)

        check_wdr = self.sh_pri.execut_db_sql(f'''show {self.config_wdr};''')
        self.log.info(check_wdr)
        if 'on' != check_wdr.splitlines()[-2].strip():
            self.sh_pri.execute_gsguc('reload',
                                      self.constant.GSGUC_SUCCESS_MSG,
                                      f'''{self.config_wdr} = "on"''')

        param1 = self.sh_pri.execut_db_sql(f'''show {self.config_wdr};''')
        self.assertEqual('on', param1.splitlines()[-2].strip(),
                         '执行失败:' + text)

        text = '-----step2:设置数据库监控快照数据的保留天数为1,设置自动对数据库监控数据执行快照操作的时间间隔为30min;' \
               'expect:设置修改参数成功-----'
        self.log.info(text)

        show_retention = f'''show {self.config_retention}'''
        check_retention = self.sh_pri.execut_db_sql(show_retention)
        self.log.info(check_retention)

        if '1' != check_retention.splitlines()[-2].strip():
            self.sh_pri.execute_gsguc('reload',
                                      self.constant.GSGUC_SUCCESS_MSG,
                                      f'''{self.config_retention} = 1''')

        param2 = self.sh_pri.execut_db_sql(show_retention)
        self.assertEqual('1', param2.splitlines()[-2].strip(),
                         '执行失败' + text)

        show_interval = f'''show {self.config_interval}'''
        check_interval = self.sh_pri.execut_db_sql(show_interval)
        self.log.info(check_interval)

        if '30min' != check_interval.splitlines()[-2].strip():
            self.sh_pri.execute_gsguc('reload',
                                      self.constant.GSGUC_SUCCESS_MSG,
                                      f'''{self.config_interval} = 30''')

        param3 = self.sh_pri.execut_db_sql(show_interval)
        self.assertEqual('30min', param3.splitlines()[-2].strip(),
                         '执行失败' + text)

        text = '-----step3:手动生成快照,循环55次;expect:生成快照数据成功-----'
        self.log.info(text)

        for i in range(55):
            select_cmd = f'''select create_wdr_snapshot();'''
            self.log.info(f'---这是第{i}次创建快照---')
            res = self.sh_pri.execut_db_sql(select_cmd, dbname='postgres')
            self.log.info(res)
            self.assertEqual('WDR snapshot request has been submitted',
                             res.splitlines()[2].strip(),
                             '执行失败:' + text)
            time.sleep(6)

        text = '-----step4:使用默认系统库，查看快照数据;' \
               'expect:查看快照数据成功，超过快照数量最大值后，snapshot_id较小的数据被清理-----'
        self.log.info(text)

        create_snap = f'''select * from {self.table};
            select count(*) from {self.table};'''
        self.log.info(create_snap)
        create_res = self.sh_pri.execut_db_sql(create_snap, dbname='postgres')
        self.log.info(create_res)
        self.assertEqual('48', create_res.splitlines()[-2].strip(),
                         '执行失败:' + text)

    def tearDown(self):
        text = '-----step5:清理环境,还原参数;expect:成功-----'
        self.log.info(text)

        drop_snapshot = f'''truncate table {self.table};
            select count(*) from {self.table};'''
        self.log.info(drop_snapshot)
        drop_res = self.sh_pri.execut_db_sql(drop_snapshot, dbname='postgres')
        self.log.info(drop_res)

        recov_wdr = self.sh_pri.execut_db_sql(f'''show {self.config_wdr};''')
        self.log.info(recov_wdr)
        if 'off' != recov_wdr.splitlines()[-2].strip():
            self.sh_pri.execute_gsguc('reload',
                                      self.constant.GSGUC_SUCCESS_MSG,
                                      f'''{self.config_wdr} = "off"''')

        show_wdr = self.sh_pri.execut_db_sql(f'''show {self.config_wdr};''')
        self.log.info(show_wdr)

        recov_retention = self.sh_pri.execut_db_sql(
            f'''show {self.config_retention}''')
        self.log.info(recov_retention)
        if '8' != recov_retention.splitlines()[-2].strip():
            self.sh_pri.execute_gsguc('reload',
                                      self.constant.GSGUC_SUCCESS_MSG,
                                      f'''{self.config_retention} = 8''')

        show_retention = self.sh_pri.execut_db_sql(
            f'''show {self.config_retention};''')

        recov_interval = self.sh_pri.execut_db_sql(
            f'''show {self.config_interval}''')
        self.log.info(recov_interval)
        if '1h' != recov_interval.splitlines()[-2].strip():
            self.sh_pri.execute_gsguc('reload',
                                      self.constant.GSGUC_SUCCESS_MSG,
                                      f'''{self.config_interval} = 60''')

        show_interval = self.sh_pri.execut_db_sql(
            f'''show {self.config_interval};''')

        self.assertEqual('off', show_wdr.splitlines()[-2].strip(), '参数恢复失败')
        self.assertEqual('8', show_retention.splitlines()[-2].strip(),
                         '参数恢复失败')
        self.assertEqual('1h', show_interval.splitlines()[-2].strip(),
                         '参数恢复失败')
        self.assertEqual('0', drop_res.splitlines()[-2].strip(),
                         '执行失败:' + text)
        self.log.info(f'----{os.path.basename(__file__)} end-----')
